%%% File    : queue.erl
%%% Author  :  <>
%%% Description : 
%%% Created : 30 Mar 2011 by  <>

-module(myqueue).

-behaviour(gen_server).

-export([start_link/1]).

-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
	terminate/2, code_change/3]).

-record(state, {id,
	       q}).

-include("whh.hrl").

%%--------
start_link(Id) ->
    Fun = fun() ->
		  mnesia:read({myqueue, Id}) end,
    {atomic, Val} = mnesia:transaction(Fun),
    case Val of
	[] ->
	    gen_server:start_link(?MODULE, [Id, undefined], []);
	[{queue, Id, Q}] ->
	    gen_server:start_link(?MODULE, [Id, Q], []);
	_Others ->
	    io:format("mnesia read id:~p info failed~n", [Id]),
	    exit('mnesia err')
    end.
	    
%%-----
init([Id, undefined]) ->
    process_flag(trap_exit, true),
    Q = queue:new(),
    Fun = fun() ->
		  mnesia:write(#myqueue{id=Id,
				     msg_queue=Q}) end,
    mnesia:transaction(Fun),
    {ok, #state{id=Id,
	       q=Q}};
init([Id, Q]) ->
    process_flag(trap_exit, true),
    update_cache({Id, self()}),
    {ok, #state{id=Id, q=Q}}.

handle_call(_Req, _From, S) ->
    {reply, ok, S}.

handle_cast(_Msg, S) ->
    {noreply, S}.

handle_info(_Info, S) ->
    {noreply, S}.

terminate(_Reason, _S) ->
    ok.

code_change(_Oldvsn, S, _Extra) ->
    {ok, S}.


%%------
update_cache(_Msg) ->
    ok.
